import 'package:flutter/material.dart';
import 'package:flutter_pin_code_fields/flutter_pin_code_fields.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/theme.dart';

import '../../constants.dart';
import 'logic.dart';

class WithdrawPage extends StatelessWidget {
  WithdrawPage({Key? key}) : super(key: key);

  final logic = Get.find<WithdrawLogic>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text('提现申请'),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Form(
        key: logic.formKey,
        child: ListView(
          padding: EdgeInsets.symmetric(
              vertical: kSpaceMedium, horizontal: kSpaceSmall),
          children: [
            // 提现金额信息
            _buildWithdrawAmount(),
            SizedBox(height: kSpaceSmall),

            // 提现银行信息
            _buildBank(),
            SizedBox(height: kSpaceSmall),

            // 附件信息
            _buildAttachment(),
            SizedBox(height: kSpaceSmall),

            // 附件信息
            Obx(() => _buildFinancialVoucher()),
            SizedBox(height: kSpaceSmall),

            // 备注信息
            _buildRemark(),
            SizedBox(height: kSpaceSmall),

            // 支付密码
            // _buildPayPassword(),
            // SizedBox(height: kSpaceSmall),

            // 提现按钮
            _buildWithdrawButton(),
            SizedBox(height: kSpaceMedium),
          ],
        ),
      ),
    );
  }

  // 生成提现按钮小部件
  Widget _buildWithdrawButton() {
    return SizedBox(
      width: double.infinity,
      height: 50,
      child: FilledButton(
        // 直角矩形样式
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(kRadiusSmall),
          ),
        ),
        onPressed: () {
          if (logic.formKey.currentState!.validate()) {
            logic.formKey.currentState!.save();
            if (logic.commonService.isAssistant()) {
              logic.submitWithdraw();
            } else {
              _showPasswordDialog();
            }
          }
        },
        child: const Text('提现'),
      ),
    );
  }

  Widget _buildRemark() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: kSpaceMedium),
          Text(
            '备注',
            style: TextStyle(
                fontSize: kFontSizeSmall, color: AppColor.colorFontBlack),
          ),
          TextFormField(
            decoration: InputDecoration(
              border: InputBorder.none,
              hintText: '请输入备注信息',
              hintStyle: TextStyle(
                fontSize: kFontSizeSmall,
                color: AppColor.colorFontLabelGrey,
              ),
              contentPadding:
                  EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
            ),
            controller: logic.remarkController,
            style: const TextStyle(color: Colors.black87),
            maxLines: 3,
          ),
          SizedBox(height: kSpaceMedium),
        ],
      ),
    );
  }

  Widget _buildAttachment() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: kSpaceMedium),
          Text(
            '附件',
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
          SizedBox(height: kSpaceSmall),
          _buildUploadAttachments(),
          SizedBox(height: kSpaceSmall),
          Text(
            '(提款时附公益小时单，给予公益服务金额1%的奖励)',
            style: TextStyle(
              fontSize: kFontSizeMini,
              color: AppColor.colorFontGrey,
            ),
          ),
          SizedBox(height: kSpaceSmall),
          Obx(
            () => Text(
              '您当前的公益费率：${logic.rating.value}',
              style: TextStyle(
                fontSize: kFontSizeMini,
                color: AppColor.colorFontRed,
              ),
            ),
          ),
          SizedBox(height: kSpaceMedium),
        ],
      ),
    );
  }

  // 财务凭证模块
  Widget _buildFinancialVoucher() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: kSpaceMedium),
          Text(
            '财务凭证',
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
          SizedBox(height: kSpaceMini),
          Text(
            '总计：${logic.invoiceTotalAmount.value}',
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
              fontWeight: AppFont.fontRegular,
            ),
          ),
          SizedBox(height: kSpaceMini),
          Center(
            child: FilledButton(
              onPressed: () => logic.toSelectInvoice(),
              child: const Text('选择发票及公益小时单'),
            ),
          ),
          SizedBox(height: kSpaceMini),
        ],
      ),
    );
  }

  Widget _buildBank() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.all(kSpaceMedium),
            child: Text(
              '提现到银行账号',
              style: TextStyle(fontSize: kFontSizeSmall, color: Colors.black87),
            ),
          ),
          const Divider(),
          SizedBox(height: kSpaceMini),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '收款人',
                  style: TextStyle(
                    fontSize: kFontSizeSmall,
                    color: AppColor.colorFontBlack,
                  ),
                ),
                Expanded(
                  child: TextFormField(
                    textAlign: TextAlign.end,
                    controller: logic.bankAccountNameController,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      contentPadding:
                          EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
                    ),
                    style: TextStyle(
                        fontSize: kFontSizeSmall,
                        color: AppColor.colorFontBlack),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入收款人姓名';
                      }
                      return null;
                    },
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '卡号',
                  style: TextStyle(
                    fontSize: kFontSizeSmall,
                    color: AppColor.colorFontBlack,
                  ),
                ),
                Expanded(
                  child: TextFormField(
                    textAlign: TextAlign.end,
                    controller: logic.bankAccountController,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      contentPadding:
                          EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
                    ),
                    keyboardType: TextInputType.number,
                    style: TextStyle(
                        fontSize: kFontSizeSmall,
                        color: AppColor.colorFontBlack),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入银行卡号';
                      }
                      return null;
                    },
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '开户行',
                  style: TextStyle(
                    fontSize: kFontSizeSmall,
                    color: AppColor.colorFontBlack,
                  ),
                ),
                Expanded(
                  child: TextFormField(
                    textAlign: TextAlign.end,
                    controller: logic.bankNameController,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      contentPadding:
                          EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
                    ),
                    style: TextStyle(
                        fontSize: kFontSizeSmall,
                        color: AppColor.colorFontBlack),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入开户行';
                      }
                      return null;
                    },
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: kSpaceMedium),
        ],
      ),
    );
  }

  Widget _buildWithdrawAmount() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: kSpaceMedium),
          Text(
            '提现金额',
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
          TextFormField(
            controller: logic.amountController,
            decoration: InputDecoration(
              icon: SvgPicture.asset('assets/icons/ic_money.svg',
                  width: kIconSizeSmall, height: kIconSizeSmall),
              contentPadding:
                  EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
              border: InputBorder.none,
            ),
            keyboardType: TextInputType.number,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入提现金额';
              }
              if (!RegExp(r'^[1-9]\d*(\.\d{1,2})?$').hasMatch(value)) {
                return '请输入正确的金额';
              }
              return null;
            },
          ),
          const Divider(),
          SizedBox(height: kSpaceSmall),
          Obx(
            () => Text(
              '可用余额 ${logic.balance.value}',
              style: TextStyle(
                fontSize: kFontSizeMini,
                color: AppColor.colorFontGrey,
              ),
            ),
          ),
          SizedBox(height: kSpaceMedium),
        ],
      ),
    );
  }

  Widget _buildUploadAttachments() {
    return Obx(
      () => Column(
        children: List.generate(
          logic.attachmentNames.length + 1,
          (index) => Container(
            margin: EdgeInsets.only(top: kSpaceTiny),
            child: FilledButton(
              onPressed: () => logic.pickFile(),
              style: ElevatedButton.styleFrom(
                foregroundColor: AppColor.colorFontBlue,
                backgroundColor: Colors.transparent,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(kRadiusSmall),
                ),
                padding: EdgeInsets.zero,
              ),
              child: Container(
                alignment: Alignment.center,
                width: double.maxFinite,
                child: index < logic.attachmentNames.length
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            logic.attachmentNames[index],
                            style: TextStyle(fontSize: kFontSizeSmall),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          //删除
                          IconButton(
                            onPressed: () => logic.deleteFile(index),
                            icon: Icon(Icons.close, size: kIconSizeTiny),
                          ),
                        ],
                      )
                    : SvgPicture.asset(
                        'assets/buttons/ic_upload.svg',
                        width: 111.5.w,
                        height: 21.w,
                      ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  void _showPasswordDialog() {
    logic.initPasswordController();
    showModalBottomSheet(
        context: Get.context!,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(15.w)),
        ),
        isScrollControlled: true,
        builder: (context) {
          return SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: kSpaceTiny),
                  Stack(
                    alignment: Alignment.center,
                    children: [
                      Align(
                        alignment: Alignment.center,
                        child: Text(
                          textAlign: TextAlign.center,
                          '请输入6位支付密码',
                          style: TextStyle(
                            fontSize: kFontSizeMedium,
                            color: AppColor.colorFontBlack,
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.centerRight,
                        child: IconButton(
                          onPressed: () => {Navigator.pop(Get.context!)},
                          icon: SvgPicture.asset(
                              'assets/icons/ic_cancel_black.svg',
                              width: kIconSizeMini),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: kSpaceTiny),
                  const Divider(),
                  SizedBox(height: kSpaceMedium),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        '往',
                        style: TextStyle(
                          fontSize: kFontSizeMedium,
                          color: AppColor.colorFontGrey,
                        ),
                      ),
                      Text(
                        ' ${logic.bankAccountNameController.text}(${logic.bankNameController.text}) ',
                        style: TextStyle(
                          fontSize: kFontSizeMedium,
                          color: AppColor.colorFontBlack,
                          fontWeight: AppFont.fontMedium,
                        ),
                      ),
                      Text(
                        '提现',
                        style: TextStyle(
                          fontSize: kFontSizeMedium,
                          color: AppColor.colorFontGrey,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: kSpaceMini),
                  Align(
                    child: Text(
                      logic.bankAccountController.text,
                      style: TextStyle(
                          fontSize: kFontSizeMini,
                          color: AppColor.colorFontGrey),
                    ),
                  ),
                  SizedBox(height: kSpaceBig),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: kSpaceLarge),
                    child: PinCodeFields(
                      length: 6,
                      autofocus: true,
                      fieldWidth: 40.w,
                      fieldHeight: 40.w,
                      padding: EdgeInsets.only(top: 4.w),
                      fieldBackgroundColor: AppColor.colorRectangleGrey,
                      fieldBorderStyle: FieldBorderStyle.square,
                      borderColor: AppColor.colorRectangleGrey,
                      activeBorderColor: AppColor.colorRectangleGrey,
                      activeBackgroundColor: AppColor.colorRectangleGrey,
                      borderRadius: BorderRadius.circular(5.w),
                      keyboardType: TextInputType.number,
                      obscureText: true,
                      textStyle: TextStyle(
                        fontSize: kFontSizeBig,
                        color: AppColor.colorFontBlack,
                      ),
                      controller: logic.payPasswordController,
                      onComplete: (text) => {
                        Get.back(),
                        logic.submitWithdraw(),
                      },
                    ),
                  ),
                  SizedBox(height: kSpaceBig),
                ],
              ),
            ),
          );
        });
  }
}
